package com.example.content.fragment.me

import android.app.Activity.RESULT_OK
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import com.bumptech.glide.Glide
import com.donkingliang.imageselector.utils.ImageSelector
import com.example.content.R
import com.example.content.activity.MainActivity
import com.example.content.databinding.PersonalInfoEditLayoutBinding
import com.example.content.fragment.BaseMvvmFragment
import com.example.content.repository.ApiService
import com.example.content.repository.bean.ModifyUserInfoReq
import com.example.content.viewmodule.me.MyPageCommonViewModel
import com.example.content.views.WheelUtils
import com.example.core.extensions.showToast
import com.example.core.network.HttpClient
import com.google.gson.reflect.TypeToken
import com.xuexiang.xui.widget.dialog.DialogLoader
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener
import com.xuexiang.xutil.net.JsonUtil
import com.xuexiang.xutil.resource.ResourceUtils
import kotlinx.android.synthetic.main.personal_info_edit_layout.*
import java.io.File

/**
 * Created by zhudongao
 * Desc
 * Date 2020/11/17
 */
class UserInfoEditFragment :
    BaseMvvmFragment<PersonalInfoEditLayoutBinding, MyPageCommonViewModel>() {

    private lateinit var sexOptions: Array<String>
    private var sexSelectOption = 0
    private var headIcon = mutableListOf("")

    override fun initView() {
        dataBinding.title.text = getString(R.string.edit_info)
        sexOptions = resources.getStringArray(R.array.sex_option)
    }

    override fun initListener() {
        dataBinding.backIcon.setOnClickListener {
            activity?.finish()
        }
        dataBinding.finish.setOnClickListener {
            val req = ModifyUserInfoReq(nickname = dataBinding.nickName.text.toString(),
            gender = sexSelectOption, address = dataBinding.liveAddress.text.toString(),
            signature = dataBinding.personalSign.text.toString())
            viewModel.modifyUserInfo(req, headIcon)
        }
        dataBinding.selectSexType.setOnClickListener {
            val option = OptionsPickerBuilder(context
            ) { _, options1, _, _ ->
                dataBinding.sexType.text = sexOptions[options1]
                sexSelectOption = options1
                false
            }
                .setTitleText("性别")
                .setSelectOptions(sexSelectOption)
                .build<String>()
            option.setPicker(sexOptions)
            option.show()
        }

        dataBinding.selectAddress.setOnClickListener {
            WheelUtils.getInstance().showAddress(context) { _, options1, options2, _ ->
                val address = "${WheelUtils.getInstance().rawProvinceInfo[options1].pickerViewText}-${WheelUtils.getInstance().citiesData[options1][options2]}"
                dataBinding.liveAddress.text = address
                false
            }
        }
        dataBinding.headerIcon.setOnClickListener {
            DialogLoader.getInstance().showContextMenuDialog(context,
            getString(R.string.header_icon_select),
            R.array.icon_menu_values)
            { dialog, which ->
                when (which) {
                    0 -> {
                        ImageSelector.builder()
                            .useCamera(false)
                            .setSingle(true)
                            .canPreview(true)
                            .start(this, REQUEST_CODE)
                        dialog.dismiss()
                    }
                    1 -> {
                        ImageSelector.builder()
                            .onlyTakePhoto(true)
                            .start(activity, REQUEST_CODE)
                        dialog.dismiss()
                    }
                    2 -> {
                        dialog.dismiss()
                    }
                }
            }
        }
        viewModel.followersData.observe(this, observer = {
            if (it.isNotEmpty()) {
                val data = it[0]
                context?.let { it1 ->
                    if (data.avatar.isNotBlank()) {
                        Glide.with(it1).load(data.avatar)
                            .into(dataBinding.headerIcon)
                    }
                }
                dataBinding.personalSign.setText(data.signature)
                if (data.gender == 0) {
                    dataBinding.sexType.text = "男"
                } else {
                    dataBinding.sexType.text = "女"
                }
                dataBinding.nickName.setText(data.nickname)
                dataBinding.liveAddress.text = data.address
            }
        })
        viewModel.responseResult.observe(this, observer = {
            if (it) {
                activity?.finish()
            } else {
                context?.showToast("修改失败")
            }
        })
    }

    override fun queryData() {
        viewModel.getUserInfo()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            val imageUrls =  data.getStringArrayListExtra(ImageSelector.SELECT_RESULT)
            if (imageUrls != null && imageUrls.size > 0) {
                context?.let {
                    headIcon.clear()
                    headIcon.addAll(imageUrls)
                    Glide.with(it).load(imageUrls[0]).into(dataBinding.headerIcon)
                }
            }
        }
    }

    override fun getLayoutId() = R.layout.personal_info_edit_layout

    companion object {
        private const val REQUEST_CODE = 1002

        @JvmStatic
        fun newInstance() = UserInfoEditFragment()
    }

    override fun getViewModuleClass(): Class<MyPageCommonViewModel> {
        return MyPageCommonViewModel::class.java
    }
}